"use client";

import React, { useRef, useState } from 'react';
import { Tag, Button, message, Modal } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import dayjs from 'dayjs';
import { getChatLogList } from '@/apis/admin/logs';
import type { ChatLog, ChatLogPageParams } from '@/types/logs';



export default function ChatLogPage() {
  const actionRef = useRef<ActionType>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<ChatLog | null>(null);



  // 查看详情
  const handleViewDetail = (record: ChatLog) => {
    setSelectedRecord(record);
    setDetailVisible(true);
  };

  // 角色标签
  const getRoleTag = (role: string) => {
    const roleMap = {
      user: { color: 'blue', text: '用户' },
      assistant: { color: 'green', text: '助手' },
      system: { color: 'orange', text: '系统' },
    };
    const config = roleMap[role as keyof typeof roleMap] || { color: 'default', text: role };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 截断内容
  const truncateContent = (content: string, maxLength: number = 50) => {
    if (content.length <= maxLength) return content;
    return content.substring(0, maxLength) + '...';
  };

  const columns: ProColumns<ChatLog>[] = [
    {
      title: '用户信息',
      key: 'student',
      width: 200,
      search: false,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{record.studentName}</div>
          <div style={{ fontSize: '12px', color: '#666' }}>{record.studentNumber}</div>
        </div>
      ),
    },
    {
      title: '搜索',
      dataIndex: 'search',
      hideInTable: true,
      valueType: 'text',
      fieldProps: {
        placeholder: '搜索学生姓名或学号',
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: 80,
      valueType: 'select',
      valueEnum: {
        user: { text: '用户', status: 'Default' },
        assistant: { text: '助手', status: 'Success' },
        system: { text: '系统', status: 'Warning' },
      },
      render: (_, record) => getRoleTag(record.role),
    },
    {
      title: '消息内容',
      dataIndex: 'content',
      width: 300,
      search: false,
      render: (_, record) => (
        <div style={{ wordBreak: 'break-word' }}>
          {truncateContent(record.content, 80)}
        </div>
      ),
    },
    {
      title: 'Token消耗',
      dataIndex: 'tokens',
      width: 100,
      search: false,
      render: (_, record) => record.tokens ? record.tokens.toLocaleString() : '-',
    },
    {
      title: '会话ID',
      dataIndex: 'chatId',
      width: 120,
      search: false,
      render: (_, record) => (
        <div style={{ fontSize: '12px', fontFamily: 'monospace' }}>
          {record.chatId ? String(record.chatId).substring(0, 8) + '...' : '-'}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 160,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startDate: value[0],
            endDate: value[1],
          };
        },
      },
      render: (_, record) => dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Button
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      <ProTable<ChatLog>
        actionRef={actionRef}
        columns={columns}
        request={async (params) => {
          try {
            const requestParams: ChatLogPageParams= {
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.search?.trim() || undefined,
              role: params.role || undefined,
              startDate: params.createdAt?.[0] ? dayjs(params.createdAt[0]).format('YYYY-MM-DD') : undefined,
              endDate: params.createdAt?.[1] ? dayjs(params.createdAt[1]).format('YYYY-MM-DD') : undefined,
            };
            const result = await getChatLogList(requestParams);
            return {
              data: result.data || [],
              total: result.total || 0,
              success: true,
            };
          } catch (error) {
            console.error('获取聊天日志失败:', error);
            message.error('获取数据失败');
            return {
              data: [],
              total: 0,
              success: false,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        scroll={{ x: 1200 }}
      />

      {/* 详情弹窗 */}
      <Modal
        title="聊天消息详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedRecord && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <strong>用户信息：</strong>{selectedRecord.studentName} ({selectedRecord.studentNumber})
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>角色：</strong>{getRoleTag(selectedRecord.role)}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>会话ID：</strong>
              <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>{selectedRecord.chatId}</span>
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>消息ID：</strong>
              <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>{selectedRecord.chatItemId}</span>
            </div>
            {selectedRecord.tokens && (
              <div style={{ marginBottom: 16 }}>
                <strong>Token消耗：</strong>{selectedRecord.tokens.toLocaleString()}
              </div>
            )}
            <div style={{ marginBottom: 16 }}>
              <strong>消息内容：</strong>
              <div style={{ 
                background: '#f5f5f5', 
                padding: 12, 
                borderRadius: 4, 
                marginTop: 8,
                maxHeight: '300px',
                overflow: 'auto',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word'
              }}>
                {selectedRecord.content}
              </div>
            </div>
            <div>
              <strong>创建时间：</strong>{dayjs(selectedRecord.createdAt).format('YYYY-MM-DD HH:mm:ss')}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}